/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package user;

import database.Database;
import database.User;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author Jack
 */
public class Profile extends javax.swing.JFrame implements ActionListener {

    /**
     * Creates new form Profile
     */
    public Profile() {
        initComponents();
        loginPanel.setVisible(true);
        userInfoPanel.setVisible(false);
        loginPanel.btnLogin.addActionListener(this);
        
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        loginPanel = new user.LoginPanel();
        userInfoPanel = new user.UserInfoPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("User Profile");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(loginPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 300, 300));
        getContentPane().add(userInfoPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 300, 300));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private user.LoginPanel loginPanel;
    private user.UserInfoPanel userInfoPanel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==loginPanel.btnLogin){
            //get user and pass from textfield
            String username=loginPanel.tfUsername.getText();
            String password=loginPanel.tfPassword.getText();
            
            //get user from database if exists
            Database.connect();
            User user=Database.login(username, password);
            //show user info if password and username correct
            if(user!=null){
                showUserData(user);
            }
            Database.shutdown();
        }
    }

    private void showUserData(User user) {
        //hide login panel
        loginPanel.setVisible(false);
        
        //populate userinfo panel and show
        userInfoPanel.setUser(user);
        userInfoPanel.setVisible(true);
    }
}
